package hotel;

import hotel.RicercaAvanzata.MyDefaultTableModel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

public class FinestraEventi extends JFrame implements ActionListener {
	ImageIcon mandaEmailImg = new ImageIcon("Risorse/mandaEmailImg.png"),
			mandaEmailATuttiImg = new ImageIcon(
					"Risorse/mandaEmailATuttiImg.png"), iconae = new ImageIcon(
					"Risorse/iconae.png");
	private static ResultSet rs = null;
	GraficaHotel g;
	private static GregorianCalendar gc1 = new GregorianCalendar();
	private GregorianCalendar gc2 = new GregorianCalendar();
	private String meseCorrente;
	private String giornoCorrente;
	private JTabbedPane tb;
	private JPanel mainPanel, pannelloTabella, pannelloBottoni,
			pannelloPrenotazioni, pannelloCheckOut,pannelloTabellaOut,pannelloAggiorna, pannelloSud,
			pannelloTabellaPre;
	private JButton mandaEmail, mandaEmailATutti,aggiorna;
	private JTable tabellaComple, tabellaPre, tabellaOut;
	private MyDefaultTableModel modelPre;
	private static MyDefaultTableModel modelOut;
	private MyDefaultTableModel modelComple;
	private JScrollPane scrollComple, scrollPre, scrollOut;
	private JRadioButton oggi, domani;
	JLabel dettagli;

	public FinestraEventi(final GraficaHotel g) {
		Image immagineIc = Toolkit.getDefaultToolkit().getImage(
				"Risorse/prenotImg1.png");
		this.setIconImage(immagineIc);
		this.g = g;
		setVisible(true);
		setTitle("Sommario Eventi");
		setLocation(350, 100);
		tb = new JTabbedPane();
		mainPanel = new JPanel();
		mainPanel.setLayout(new BorderLayout());
		pannelloTabella = new JPanel();
		pannelloTabella.setLayout(new BorderLayout());
		pannelloBottoni = new JPanel();

		// pannello compleanni
		creaTabellaCompleanni();
		tabellaComple = new JTable(modelComple);
		tabellaComple.setGridColor(Color.LIGHT_GRAY);
		scrollComple = new JScrollPane(tabellaComple);
		JTableHeader header1 = tabellaComple.getTableHeader();
		header1.setReorderingAllowed(false);
		mandaEmail = new JButton("Manda Email");
		mandaEmail.setIcon(mandaEmailImg);
		mandaEmail.addActionListener(this);
		mandaEmailATutti = new JButton("Manda Email a tutti");
		mandaEmailATutti.setIcon(mandaEmailATuttiImg);
		mandaEmailATutti.addActionListener(this);
		pannelloBottoni.add(mandaEmail);
		pannelloBottoni.add(mandaEmailATutti);
		pannelloTabella.add(header1, BorderLayout.PAGE_START);
		pannelloTabella.add(scrollComple, BorderLayout.CENTER);
		mainPanel.add(pannelloTabella);
		mainPanel.add(pannelloBottoni, BorderLayout.SOUTH);

		// pannello prenotazioni 
		pannelloPrenotazioni = new JPanel();
		pannelloTabellaPre = new JPanel();
		pannelloSud = new JPanel();
		pannelloPrenotazioni.setLayout(new BorderLayout());
		gc2.add(GregorianCalendar.DATE, 1);
		modelPre = new MyDefaultTableModel();
		modelPre.addColumn("Camera");
		modelPre.addColumn("Fino Al");
		modelPre.addColumn("Nominativo");
		oggi = new JRadioButton("Oggi", true);
		oggi.addActionListener(this);
		domani = new JRadioButton("Domani");
		domani.addActionListener(this);
		ButtonGroup bgg = new ButtonGroup();
		bgg.add(oggi);
		bgg.add(domani);
		aggiornaTabellaPrenotazioni();
		tabellaPre = new JTable(modelPre);
		scrollPre = new JScrollPane(tabellaPre);
		JTableHeader header2 = tabellaPre.getTableHeader();
		header2.setReorderingAllowed(false);
		pannelloSud.add(oggi);
		pannelloSud.add(domani);
		pannelloTabellaPre.add(header2, BorderLayout.PAGE_START);
		pannelloTabellaPre.add(scrollPre, BorderLayout.CENTER);
		pannelloPrenotazioni.add(pannelloTabellaPre, BorderLayout.CENTER);
		pannelloPrenotazioni.add(pannelloSud, BorderLayout.SOUTH);

		// pannello Check-Out 
		pannelloCheckOut = new JPanel();
		pannelloCheckOut.setLayout(new BorderLayout());
		pannelloAggiorna=new JPanel();
		pannelloTabellaOut=new JPanel();
		pannelloTabellaOut.setLayout(new BorderLayout());
		aggiorna=new JButton("Aggiorna");
		aggiorna.addActionListener(this);
		modelOut = new MyDefaultTableModel();
		modelOut.addColumn("Camera");
		aggiornaTabellaOut();
		tabellaOut = new JTable(modelOut);
		tabellaOut.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tabellaOut.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					new FinestraCamera(g, (String) target
							.getValueAt(row, 0)).setVisible(true);

				}
			}
		});
		scrollOut = new JScrollPane(tabellaOut);
		JTableHeader header3 = tabellaOut.getTableHeader();
		header3.setReorderingAllowed(false);
		dettagli=new JLabel("Doppio-click sulla camera per entare nei suoi dettagli.");
		pannelloTabellaOut.add(header3,BorderLayout.PAGE_START);
		pannelloTabellaOut.add(scrollOut,BorderLayout.CENTER);
		pannelloAggiorna.add(aggiorna);
		pannelloCheckOut.add(dettagli,BorderLayout.NORTH);
		pannelloCheckOut.add(pannelloTabellaOut,BorderLayout.CENTER);
		pannelloCheckOut.add(pannelloAggiorna,BorderLayout.SOUTH);

		tb.add(mainPanel, "Compleanni di Oggi");
		tb.add(pannelloPrenotazioni, "Prenotazioni vicine");
		tb.add(pannelloCheckOut, "Check-Out di Oggi");
		add(tb);
		pack();

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == mandaEmail) {
			int[] rows = tabellaComple.getSelectedRows();
			if (modelComple.getRowCount() < 1) {
				JOptionPane.showMessageDialog(null,
						"Non ci sono compleanni oggi.", "Avviso",
						JOptionPane.WARNING_MESSAGE, iconae);
			} else if (rows.length > 0) {
				StringBuilder sb = new StringBuilder();
				sb.append("mailto:");
				for (int i = 0; i < rows.length; i++) {
					sb.append(modelComple.getValueAt(rows[i], 2));
					if (i < (modelComple.getRowCount() - 2)
							&& !modelComple.getValueAt(i, 2).equals(""))
						sb.append(",");
				}

				String nome = g.nomeHotel.replace(" ", "%20");
				sb.append("?subject=Buon%20Compleanno&body=L'Hotel%20" + nome
						+ "%20le%20augura%20Buon%20Compleanno.");
				try {
					Desktop.getDesktop().mail(new URI(sb.toString()));
				} catch (IOException | URISyntaxException exc) {
					exc.printStackTrace();
				}
			} else
				JOptionPane.showMessageDialog(null,
						"Seleziona almeno un cliente!", "Avviso",
						JOptionPane.WARNING_MESSAGE, iconae);
		} else if (e.getSource() == mandaEmailATutti) {
			if (modelComple.getRowCount() > 0) {
				StringBuilder sb = new StringBuilder();
				sb.append("mailto:");
				for (int i = 0; i < modelComple.getRowCount(); i++) {
					sb.append(modelComple.getValueAt(i, 2));
					if (i < (modelComple.getRowCount() - 2)
							&& !modelComple.getValueAt(i, 2).equals(""))
						sb.append(",");
				}
				String nome = g.nomeHotel.replace(" ", "%20");
				sb.append("?subject=Buon%20Compleanno&body=L'Hotel%20" + nome
						+ "%20le%20augura%20Buon%20Compleanno.");
				try {
					Desktop.getDesktop().mail(new URI(sb.toString()));
				} catch (IOException | URISyntaxException exc) {
					exc.printStackTrace();
				}
			} else
				JOptionPane.showMessageDialog(null,
						"Non ci sono compleanni oggi.", "Avviso",
						JOptionPane.WARNING_MESSAGE, iconae);
		} else if (e.getSource() == oggi) {
			aggiornaTabellaPrenotazioni();
		} else if (e.getSource() == domani) {
			aggiornaTabellaPrenotazioni();
		}else if(e.getSource()==aggiorna){
			aggiornaTabellaOut();
		}
	}

	private void creaTabellaCompleanni() {
		modelComple = new MyDefaultTableModel();
		modelComple.addColumn("Nome");
		modelComple.addColumn("Cognome");
		modelComple.addColumn("Email");
		DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
		String s = f.format(gc1.getTime());
		try {
			rs = GraficaHotel.database.stat
					.executeQuery("SELECT nome,cognome,email FROM CLIENTI where datadinascita like '%"
							+ s.substring(s.indexOf("-")) + "'");
			ResultSetMetaData md = rs.getMetaData();
			int columnCount = md.getColumnCount();
			Vector<String> row;
			while (rs.next()) {
				row = new Vector<String>(columnCount);
				for (int i = 1; i <= columnCount; i++) {
					row.add(rs.getString(i));
				}
				modelComple.addRow(row);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}// creaTabellaCompleanni

	public static void aggiornaTabellaOut() {
		modelOut.setRowCount(0);
		DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
		String s = f.format(gc1.getTime());
		try {
			rs = GraficaHotel.database.stat
					.executeQuery("SELECT camera FROM ASSOCIAZIONE where datadipartenza='"
							+ s + "'");
			ResultSetMetaData md = rs.getMetaData();
			int columnCount = md.getColumnCount();
			Vector<String> row;
			while (rs.next()) {
				row = new Vector<String>(columnCount);
				for (int i = 1; i <= columnCount; i++) {
					row.add(rs.getString(i));
				}
				modelOut.addRow(row);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}// aggiornaTabellaOut

	private void aggiornaTabellaPrenotazioni() {
		modelPre.setRowCount(0);
		DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
		String s = null;
		if (oggi.isSelected())
			s = f.format(gc1.getTime());
		else
			s = f.format(gc2.getTime());
		try {
			rs = GraficaHotel.database.stat
					.executeQuery("SELECT camera,DATE_FORMAT(al,'%d/%m/%Y'),nominativo FROM PRENOTAZIONI where dal='"
							+ s + "'");
			ResultSetMetaData md = rs.getMetaData();
			int columnCount = md.getColumnCount();
			Vector<String> row;
			while (rs.next()) {
				row = new Vector<String>(columnCount);
				for (int i = 1; i <= columnCount; i++) {
					row.add(rs.getString(i));
				}
				modelPre.addRow(row);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}// creaTabellaPrenotazioni

	class MyDefaultTableModel extends DefaultTableModel {
		private static final long serialVersionUID = 1L;

		public boolean isCellEditable(int row, int column) {
			return false;
		}
	}

}
